/**
 * uni-app HTTP请求工具
 * 封装uni.request，提供统一的API调用接口
 */

import appConfig from './config.js'

// 后端API基础URL
const BASE_URL = appConfig.API_BASE_URL

/**
 * 发起HTTP请求
 * @param {Object} options 请求配置
 * @returns {Promise} 返回Promise对象
 */
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 获取token
    const token = uni.getStorageSync('token')
    
    // 构建请求配置
    const config = {
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      timeout: options.timeout || 60000
    }
    
    // 添加Authorization头
    if (token) {
      config.header.Authorization = `Bearer ${token}`
    }
    
    // 记录请求日志
    if (appConfig.DEBUG) {
      console.log('发起API请求:', {
        url: config.url,
        method: config.method,
        data: config.data,
        headers: config.header
      })
    }
    
    // 发起请求
    uni.request({
      ...config,
      success: (res) => {
        if (appConfig.DEBUG) {
          console.log('API请求成功:', options.url, res)
        }
        
        // 检查HTTP状态码
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          console.error('API请求失败:', {
            url: options.url,
            statusCode: res.statusCode,
            data: res.data
          })
          
          // 根据状态码提供更具体的错误信息
          let errorMessage = '请求失败'
          if (res.statusCode === 401) {
            errorMessage = '未授权访问，请重新登录'
          } else if (res.statusCode === 403) {
            errorMessage = '访问被禁止'
          } else if (res.statusCode === 404) {
            errorMessage = '请求的资源不存在'
          } else if (res.statusCode === 500) {
            errorMessage = '服务器内部错误'
          } else if (res.data?.message) {
            errorMessage = res.data.message
          }
          
          reject(new Error(`HTTP ${res.statusCode}: ${errorMessage}`))
        }
      },
      fail: (err) => {
        console.error('API请求异常:', {
          url: options.url,
          error: err
        })
        
        // 处理网络错误
        if (err.errMsg.includes('timeout')) {
          reject(new Error('请求超时，请检查网络连接'))
        } else if (err.errMsg.includes('fail request:ssl')) {
          reject(new Error('SSL连接失败，请检查服务器证书'))
        } else if (err.errMsg.includes('fail')) {
          reject(new Error('网络连接失败，请检查网络'))
        } else {
          reject(new Error(err.errMsg || '请求失败'))
        }
      }
    })
  })
}

/**
 * GET请求
 */
const get = (url, params = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    ...options
  })
}

/**
 * POST请求
 */
const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

/**
 * PUT请求
 */
const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

/**
 * DELETE请求
 */
const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

export default {
  request,
  get,
  post,
  put,
  delete: del
} 